package com.IOT_LSL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Fragment_wifi extends Fragment {
    private View view;
    private Button tcp_client;
    private Button send_data;
    private EditText edit_ip;
    private EditText edit_port;
    private EditText send_text;
    private EditText recv_text;
    private TextView fragment_ctl_message;

    public OutputStream outputStream = null;
    public InputStream inputStream = null;
    public LineChart line_chart_temp = null;
    public LineDataSet set1 = null;
    public LineDataSet set2 = null;
    public int count = 0;

    private Socket mSocket = null;
    private static final String TAG = "TCP";
    private String app_text,receData;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        fragment_ctl_message = (TextView) getActivity().findViewById(R.id.fragment_ctl_message);
        line_chart_temp = (LineChart) getActivity().findViewById(R.id.line_chart_view);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_wifi,container,false);
        InitVIew();
        return view;
    }

    private void InitVIew() {
        set1 = ((MainActivity)getActivity()).getSet1();
        set2 = ((MainActivity)getActivity()).getSet2();
        tcp_client = view.findViewById(R.id.btn_tcp_client);
        send_data = view.findViewById(R.id.btn_send);
        edit_ip = view.findViewById(R.id.edit_ip);
        edit_port = view.findViewById(R.id.edit_port);
        send_text = view.findViewById(R.id.fragment_wifi_send_edittext);
        recv_text = view.findViewById(R.id.fragment_wifi_recv_edittext);
        recv_text.setInputType(InputType.TYPE_NULL);
        tcp_client.setBackgroundColor(getResources().getColor(R.color.purple_700));
        send_data.setBackgroundColor(getResources().getColor(R.color.purple_700));

        tcp_client.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ip = edit_ip.getText().toString();
                String port = edit_port.getText().toString();
                if (ip.isEmpty() || port.isEmpty()) {
                    if (ip.isEmpty() && port.isEmpty())
                        Toast.makeText(getActivity(), "请输入IP地址和端口号", Toast.LENGTH_SHORT).show();
                    else if (port.isEmpty())
                        Toast.makeText(getActivity(), "端口号不能为空", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(getActivity(), "IP地址不能为空", Toast.LENGTH_SHORT).show();
                }
                String BtnContent = tcp_client.getText().toString();
                if (BtnContent.equals("启动TCP连接")) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mSocket = new Socket(ip, Integer.parseInt(port));
                                if (mSocket.isConnected()) {
                                    Log.i(TAG, "TCP连接成功！");
                                } else {
                                    return;
                                }
                                inputStream = mSocket.getInputStream();
                                outputStream = mSocket.getOutputStream();
                                ((MainActivity)getActivity()).set_tcp_outputStream(outputStream);
                                ((MainActivity)getActivity()).set_tcp_inputStream(inputStream);
                                tcp_client.setText("停止TCP连接");
                                tcp_client.setBackgroundColor(getResources().getColor(R.color.teal_200));
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        while (mSocket.isConnected()) {
                                            byte[] buf = new byte[1024];
                                            int len = 0;
                                            try {
                                                len = inputStream.read(buf);
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                            receData = new String(buf, 0, len, Charset.forName("ASCII"));
                                            Log.i(TAG, receData);
                                            /////////////////////////////////////
                                            char[] tmp = receData.toCharArray();
                                            if( tmp[0] != 'T' ) {
                                                getActivity().runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        recv_text.setText(receData);
                                                        fragment_ctl_message.setText(receData);
                                                    }
                                                });
                                            }else if( tmp[0] == 'T' && count < 100 ){
                                                int temp_val = 10*(tmp[2]-'0')+tmp[3]-'0';
                                                int humi_val = 10*(tmp[9]-'0')+tmp[10]-'0';
                                                addEntry(temp_val,0);
                                                addEntry(humi_val,1);
                                                count++;
                                            }
                                            /////////////////////////////////////
                                        }
                                    }
                                }).start();
                            } catch (IOException e) {
                                e.printStackTrace();
                                Log.i(TAG, "连接失败！！!" + e.toString());
                            }
                        }
                    }).start();
                } else {
                    tcp_client.setText("启动TCP连接");
                    tcp_client.setBackgroundColor(getResources().getColor(R.color.purple_700));
                    try {
                        mSocket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        send_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        app_text = send_text.getText().toString().trim();
                        try {
                            if (app_text.equals("")) {
                                Log.i(TAG, "输入不能为空");
                            } else {
                                if (outputStream != null) {
                                    byte[] sendData = app_text.getBytes(Charset.forName("ASCII"));
                                    outputStream.write(sendData, 0, sendData.length);
                                    outputStream.flush();
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    public void addEntry(int yValues,int index){
        LineData data = line_chart_temp.getLineData();
        LineDataSet set = (LineDataSet) data.getDataSetByIndex(index);
        Entry entry = new Entry(count,yValues);
        set.addEntry(entry);

        if(count>4){
            line_chart_temp.moveViewToX(count-4);
        }
        line_chart_temp.notifyDataSetChanged();
        line_chart_temp.invalidate();
    }
}
